from app.database.postgre import SessionDep, col
from app.database.models import Account, App, RechargeLog
from app.models import responses
from app.models.common import AppIdJSON
from app.models.recharge_logs import AppRechargeLogListParams


async def get_recharge_logs_list(
        account: Account,
        query_params: AppRechargeLogListParams,
        session: SessionDep
):
    """获取筛选后的充值日志"""
    # 构建查询参数
    app_id = query_params.app_id
    page = query_params.page
    page_size = query_params.page_size
    origin_card = query_params.origin_card
    used_card = query_params.used_card
    recharge_ip = query_params.recharge_ip

    # 获取查询的应用
    app = session.get(App, query_params.app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 创建筛选条件
    query = session.query(RechargeLog).filter(RechargeLog.app_id == app_id).order_by(col(RechargeLog.id).desc())

    if origin_card:
        query = query.filter(col(RechargeLog.origin_card).like(f"%{origin_card}%"))

    if used_card:
        query = query.filter(col(RechargeLog.used_card).like(f"%{used_card}%"))

    if recharge_ip:
        query = query.filter(col(RechargeLog.recharge_ip).like(f"%{recharge_ip}%"))

    # 获取筛选后的总数
    total_count = query.count()
    total_pages = (total_count + page_size - 1) // page_size

    # 对筛选后的数据进行分页
    offset = (page - 1) * page_size
    paginated_query = query.offset(offset).limit(page_size)
    paginated_logs = paginated_query.all()

    return responses.SuccessResponse(
        data={
            'total': total_count,
            'total_pages': total_pages,
            'page': page,
            'page_size': len(paginated_logs),
            'list': [log.model_dump() for log in paginated_logs]
        }
    )


async def clear_all_recharge_logs(account: Account, json_data: AppIdJSON, session: SessionDep):
    """清空所有的充值日志"""
    # 获取对应的应用
    app_id = json_data.app_id
    app = session.get(App, app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 检查应用是否被超管禁用
    if app.force_disabled:
        return responses.Response304()

    # 获取该应用的所有日志
    logs = session.query(RechargeLog).filter(RechargeLog.app_id == app_id).all()
    if not logs:
        return responses.SuccessResponse(msg='该应用没有充值日志', data={'ids': []})

    deleted_ids = [log.id for log in logs]

    session.query(RechargeLog).filter(RechargeLog.app_id == app_id).delete(synchronize_session=False)
    session.commit()

    return responses.SuccessResponse(msg='充值日志已清空', data={
        'ids': deleted_ids
    })
